#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

void handler(int signum)
{
    sleep(3);
    pid_t rid;
    // 如果同一时间有多个子进程退出，则循环调用，直到目前没有子进程退出为止
    while ((rid = waitpid(-1, nullptr, 0)) && rid > 0)
    {
        cout << "I am  process " << getpid() << ", received signal " << signum << endl;
        cout << "Child process " << rid << " terminated" << endl;
    }
}

int main()
{
    signal(17, SIG_IGN);

    for (int i = 0; i < 10; i++)
    {
        pid_t pid = fork();
        if (pid == 0)
        {
            // child
            while (true)
            {
                cout << "Child process ,pid:" << getpid() << endl;
                sleep(rand() % 5 + 1); // 子进程随机停留一段时间

                break;
            }
            cout << "Child process exit" << endl;
            exit(0);
        }
        sleep(1);
    }

    // father
    while (true)
    {
        cout << "Father process,pid:" << getpid() << endl;
        sleep(1);
    }
    return 0;
}

